//
//  JieRuJieChuVC.m
//  BrushFace
//
//  Created by timer_q on 15/12/25.
//  Copyright © 2015年 Zzz. All rights reserved.
//

#import "JieRuJieChuVC.h"
#import "JieChuCell.h"
#import "JieRuCell.h"
#import "MySceneModel.h"
#import "NavHelper.h"
#import "IWillHelper.h"
#import "AppStatus.h"
#import "ChooseCell.h"
@interface JieRuJieChuVC ()<UITableViewDataSource,UITableViewDelegate>
{
    FINANCE_TYPE _currentType;
    UITableView *_tableView;
    UITableView *_chooseTableView;
    UILabel *_daiShouLabel;
    UILabel *_benJinLabel;
    NSString *_currType;
    int _requestPage;
    NSArray *_filterArray;
}
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)MySceneModel *myModel;
@end

@implementation JieRuJieChuVC
- (instancetype)initWithType:(FINANCE_TYPE)type{
    self = [super init];
    if (self) {
        _currentType = type;
        /**
         *  全部 100
         *  借款中 0-1-11-12-0
         *  已流标 7-6
         *  已还款 10-8
         *  满标   2-700
         *  还款中  4-3-13-9
         *  逾期  5
         */
        _currType = @"100";
        _isBorrowing = NO;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (_isBorrowing == YES) {
        _currType = @"0-1-11-12-0";
    }
    [self UIConfig];
    [self dataInit];
    
}
- (void)leftButtonClick{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - CustomMethod
- (void)UIConfig{
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(0, 63.5, SCREEN_WIDTH, 0.5)];
    line2.backgroundColor = [UIColor lightGrayColor];
    [self.navBar addSubview:line2];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = UIColorFromRGB(ColorValueForBackView_Gray);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.tableHeaderView = [self tableViewHeaderView];
    [self.view addSubview:_tableView];
    
    [self setRefresh];
    [self filterTableViewCreate];
}

- (void)filterTableViewCreate{
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 20, SCREEN_WIDTH-200, 44)];
    [self.view addSubview:button];
    button.selected = NO;
    [button addTarget:self action:@selector(showChooeseView:) forControlEvents:UIControlEventTouchUpInside];
    
    _filterArray = @[@"0-1-11-12-0",@"4-3-13-9",@"7-6",@"2-700",@"10-8",@"5",@"100"];
    _chooseTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, 0) style:UITableViewStylePlain];
    _chooseTableView.delegate = self;
    _chooseTableView.dataSource = self;
    _chooseTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.view addSubview:_chooseTableView];

}
- (void)dataInit{
    [self.navBar setLeftBtn:NAV_BAR_LEFT_BTN_TYPE_BLUE];
    _myModel = [MySceneModel SceneModel];
    if (_currentType==JIECHU_TYPE) {
        _requestPage = 0;
        _dataArray = [[NSMutableArray alloc] init];
        [_myModel hope_listMyBorrowOutForApp:0 andRPP:10 andType:_currType andCB:^(NSDictionary *rqOutput) {
            [_dataArray removeAllObjects];
            [_dataArray addObjectsFromArray:[rqOutput objectForKey:@"data"]];
            [_tableView reloadData];
        }];
        [self.navBar setTitle:@"借出记录"];
    }else{
        _requestPage = 0;
        _dataArray = [[NSMutableArray alloc] init];
        [_myModel user_listMyReplanWithCurPage:0 andRPP:10 andType:_currType andCB:^(NSDictionary *rqOutput) {
            [_dataArray removeAllObjects];
            [_dataArray addObjectsFromArray:[rqOutput objectForKey:@"data"]];
            [_tableView reloadData];
        }];
        [self.navBar setTitle:@"借入记录"];
    }
    
    [_myModel user_getToInComeForAppCB:^(id output) {
        NSString *daiShouCurr;
        NSString *daiShouAll;
        if (_currentType == JIECHU_TYPE) {
            daiShouCurr =[NSString stringWithFormat:@"%@",[output objectForKey:@"toincomeinterest"]];
            daiShouAll = [NSString stringWithFormat:@"%@",[output objectForKey:@"toincomecapital"]];
        }else{
            daiShouCurr =[NSString stringWithFormat:@"%@",[output objectForKey:@"torepayinterest"]];
            daiShouAll = [NSString stringWithFormat:@"%@",[output objectForKey:@"torepaycapital"]];
        }
        
        _daiShouLabel.text = [daiShouCurr isEqual:[NSNull null]]?@"0.00":daiShouCurr;
        _benJinLabel.text = [daiShouAll isEqual:[NSNull null]]?@"0.00":daiShouAll;
    }];
}
- (UIView *)tableViewHeaderView{

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    headerView.backgroundColor = [UIColor whiteColor];
    UIView *subView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH*0.5, 50)];
    [headerView addSubview:subView1];
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(subView1.frame.size.width-0.25, 0, 0.5, 50)];
    line1.backgroundColor = [UIColor lightGrayColor];
    [headerView addSubview:line1];
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.5)];
    line2.backgroundColor = [UIColor lightGrayColor];
    //[headerView addSubview:line2];
    UIView *subView2 = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH*0.5, 0, SCREEN_WIDTH*0.5, 50)];
    [headerView addSubview:subView2];
    
    for (int i=0; i<2; i++) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 9, subView1.frame.size.width, 16)];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = ColorDefaultOrange;
        label.text = @"0.00";
        
        UILabel *buZYlabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 25, subView1.frame.size.width, 12)];
        buZYlabel.textAlignment = NSTextAlignmentCenter;
        buZYlabel.font = [UIFont systemFontOfSize:11];
        buZYlabel.textColor = [UIColor lightGrayColor];
        if (i==0) {
            if (_currentType == JIECHU_TYPE) {
                buZYlabel.text = @"待收收益(元)";
            }else{
                buZYlabel.text = @"待还收益(元)";
            }
            _daiShouLabel = label;
            [subView1 addSubview:_daiShouLabel];
            [subView1 addSubview:buZYlabel];
        }else{
            if (_currentType == JIECHU_TYPE) {
                buZYlabel.text = @"待收本金(元)";
            }else{
                buZYlabel.text = @"待还本金(元)";
            }
            
            _benJinLabel = label;
            [subView2 addSubview:_benJinLabel];
            [subView2 addSubview:buZYlabel];
        }
    }
    return headerView;
}

- (void)setRefresh{
    @weakify (self);
    [_tableView addPullToRefreshWithActionHandler:^{
        @strongify (self);
        self->_requestPage = 0;
        if (_currentType == JIECHU_TYPE) {
            [self.myModel hope_listMyBorrowOutForApp:0 andRPP:10 andType:self->_currType andCB:^(NSDictionary *rqOutput) {
                [self->_dataArray removeAllObjects];
                [self->_dataArray addObjectsFromArray:[rqOutput objectForKey:@"data"]];
                [self->_tableView reloadData];
                [self->_tableView endAllRefreshingWithEnd:NO];
            }];
        }else{
            [self.myModel user_listMyReplanWithCurPage:0 andRPP:10 andType:self->_currType andCB:^(NSDictionary *rqOutput) {
                [self->_dataArray removeAllObjects];
                [self->_dataArray addObjectsFromArray:[rqOutput objectForKey:@"data"]];
                [self->_tableView reloadData];
                if ([[rqOutput objectForKey:@"data"] count]<10) {
                    [self->_tableView endAllRefreshingWithEnd:YES];
                }else{
                [self->_tableView endAllRefreshingWithEnd:NO];
                }
                
            }];
        }
    }];
    [_tableView addInfiniteScrollingWithActionHandler:^{
        @strongify (self);
        if (_currentType == JIERU_TYPE) {
            [self.myModel user_listMyReplanWithCurPage:++self->_requestPage andRPP:10  andType:self->_currType andCB:^(NSDictionary *rqOutput) {
                [self->_dataArray addObjectsFromArray:[rqOutput objectForKey:@"data"]];
                [self->_tableView reloadData];
                [self->_tableView endAllRefreshingWithEnd:NO];
            }];
        }else{
            [self.myModel hope_listMyBorrowOutForApp:++self->_requestPage andRPP:10 andType:self->_currType andCB:^(NSDictionary *rqOutput) {
                [self->_dataArray addObjectsFromArray:[rqOutput objectForKey:@"data"]];
                [self->_tableView reloadData];
                if ([[rqOutput objectForKey:@"data"] count]<10) {
                    [self->_tableView endAllRefreshingWithEnd:YES];
                }else{
                    [self->_tableView endAllRefreshingWithEnd:NO];
                }
            }];

        }
    }];
    
}

#pragma mark - tableViewDelegate and DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView == _chooseTableView) {
        return 1;
    }
    return _dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _chooseTableView) {
        return 7;
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == _chooseTableView) {
        return 0;
    }
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _chooseTableView) {
        return 40;
    }
    if (_currentType == JIECHU_TYPE) {
        return 120;
    }else{
        return 80;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _chooseTableView) {
        NSArray *arr = @[@"借款中",@"还款中",@"已流标",@"已满标",@"已还款",@"逾期",@"全部"];
        ChooseCell *cell = [ChooseCell loadBundleNib];
        cell.celltitle.text = [arr objectAtIndex:indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if ([_filterArray indexOfObject:_currType] == indexPath.row) {
            cell.cellImage.image = [UIImage imageNamed:@"yixuanze"];
        }else{
            cell.cellImage.image = [UIImage imageNamed:@"weixuan"];
        }
        return cell;
    }
    if (_currentType == JIECHU_TYPE) {
        static NSString *cellID = @"JieChuCell";
        JieChuCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [JieChuCell loadBundleNib];
        }
        NSDictionary *responseDict = [_dataArray objectAtIndex:indexPath.section];
        NSInteger type = [[responseDict objectForKey:@"hopestatus1"] integerValue];
        [cell cellType:type];
        cell.hopeID = [responseDict objectForKey:@"hopeid"];
        [cell.cellHeaderImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HEADERIMAGE_FETCH,[responseDict objectForKey:@"localid"]]] placeholderImage:nil];
        cell.cellNameLabel.text = [responseDict objectForKey:@"name"];
        cell.cellReasonLabel.text = [responseDict objectForKey:@"content"];
        cell.cellMoneyLabel.text = [NSString stringWithFormat:@"%@",[responseDict objectForKey:@"amount"]];
        NSString *yihuoStr = [NSString stringWithFormat:@"%@",[responseDict objectForKey:@"alincome"]];
        if ([yihuoStr isEqualToString:@"-1"]) {
            yihuoStr = @"未放款";
        }
        cell.cellShouYiLabel.text = yihuoStr;
        NSString *daihuoStr = [NSString stringWithFormat:@"%@",[responseDict objectForKey:@"toincome"]];
        if ([daihuoStr isEqualToString:@"-1"]) {
            daihuoStr = @"未放款";
        }
        cell.cellDaiHuoShouLabel.text = daihuoStr;
        cell.userid = [responseDict objectForKey:@"localid"];
        NSString *incoming = responseDict[@"incoming"];
        NSString *amount = responseDict[@"amount"];
        if (type == AR_BORROW_ING||type==0||type==11||type==12) {
            CGFloat bili = [incoming floatValue]/[amount floatValue];
            [cell.process setConstant:cell.processBackView.frame.size.width*bili];
        }
        return cell;
    }else{
        static NSString *cellID = @"JieRuCell";
        JieRuCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [JieRuCell loadBundleNib];
        }
        NSDictionary *responseDict = [_dataArray objectAtIndex:indexPath.section];
        NSInteger type = [[responseDict objectForKey:@"status"] integerValue];
        [cell cellType:type];
        if (type == 1) {
            cell.cellDownLabel.text = [responseDict objectForKey:@"investamount"];
        }
        NSString *lixiStr = [[responseDict objectForKey:@"hoperate"] stringValue];
        NSArray *lixiArr = [lixiStr componentsSeparatedByString:@"."];
        cell.cellLiXiLabel.text = [lixiArr firstObject];
        if (lixiArr.count == 2) {
            cell.cellLiXiLittleLabel.text = [NSString stringWithFormat:@".%@",[lixiArr lastObject]];
        }else{
            cell.cellLiXiLittleLabel.text = @".00";
        }
        cell.cellMoneyLabel.text = [responseDict objectForKey:@"hopeamount"];
        if ([[responseDict objectForKey:@"priod"] integerValue]==0) {
            cell.cellDateLabel.text = [NSString stringWithFormat:@"%@天",[responseDict objectForKey:@"days"]];
        }else{
            cell.cellDateLabel.text = [NSString stringWithFormat:@"%@个月",[responseDict objectForKey:@"priod"]];
        }
        cell.hopeID = [responseDict objectForKey:@"id"];
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (tableView == _chooseTableView) {
        _currType = [_filterArray objectAtIndex:indexPath.row];
        if (_currentType==JIECHU_TYPE) {
            _requestPage = 0;
            _dataArray = [[NSMutableArray alloc] init];
            [_myModel hope_listMyBorrowOutForApp:0 andRPP:10 andType:_currType andCB:^(NSDictionary *rqOutput) {
                [_dataArray removeAllObjects];
                [_dataArray addObjectsFromArray:[rqOutput objectForKey:@"data"]];
                [_tableView reloadData];
            }];
            [self.navBar setTitle:@"借出记录"];
        }else{
            _requestPage = 0;
            _dataArray = [[NSMutableArray alloc] init];
            [_myModel user_listMyReplanWithCurPage:0 andRPP:10 andType:_currType andCB:^(NSDictionary *rqOutput) {
                [_dataArray removeAllObjects];
                [_dataArray addObjectsFromArray:[rqOutput objectForKey:@"data"]];
                [_tableView reloadData];
            }];
            [self.navBar setTitle:@"借入记录"];
        }
        [_chooseTableView reloadData];
        [UIView animateWithDuration:0.3 animations:^{
            _chooseTableView.frame = CGRectMake(0, 64, SCREEN_WIDTH, 0);
        }];
        
        return;
    }
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (_currentType == JIECHU_TYPE) {
        JieChuCell *currentCell = (JieChuCell *)cell;
        [NavHelper gotoAssetsRecordVC:currentCell.currentType andBaseType:TYPE_BORROW_OUT andHopeId:currentCell.hopeID];
    }else{
        JieRuCell *currentCell = (JieRuCell *)cell;
        [IWillHelper sharedInstance].hopeid = currentCell.hopeID;
        if (currentCell.currentType==1) {
            [AppStatus sharedInstance].radarBackType = ENUM_BORROW_IN;
            [NavHelper gotoBorrowingColorVCWithHopeID:currentCell.hopeID];
            return;
        }
        [NavHelper gotoAssetsRecordVC:currentCell.currentType andBaseType:TYPE_BORROW_IN andHopeId:currentCell.hopeID];
    }
}



- (void)showChooeseView:(UIButton *)sender{
    if (sender.selected == NO) {
        sender.selected = YES;
        [UIView animateWithDuration:0.3 animations:^{
            _chooseTableView.frame = CGRectMake(0, 64, SCREEN_WIDTH, 280);
        }];
    }else{
        [UIView animateWithDuration:0.3 animations:^{
            _chooseTableView.frame = CGRectMake(0, 64, SCREEN_WIDTH, 0);
        }];
        sender.selected = NO;
    
    }

}
@end
